<template>
	<view>
		<!-- 录音插件 -->
		<recorder v-if="isHttps" @getData="getRecorderData" style="position: fixed;bottom: 200rpx;right: 50rpx;z-index: 9;"></recorder>

		<view class="card tn-padding-sm tn-margin-sm">
			<tn-form :model="form" ref="form" :labelWidth="180" :errorType="['message', 'toast']">
				<tn-form-item label="救援类型：" prop="accidentType">
					<tn-input type="select" :selectOpen="jiuyuanleixingshow" @click="jiuyuanleixingshow = true"
						v-model="form.accidentType" />
				</tn-form-item>
				<tn-form-item label="发生时间：" prop="occutTime">
				  <uni-datetime-picker :clearIcon="false" :border="false" placeholder="请选择发生时间"
									   v-model="form.occutTime" />
				</tn-form-item>

				<tn-form-item label="当事人：" prop="caller">
					<tn-input v-model="form.caller" />
				</tn-form-item>
				<tn-form-item label="手机号：" prop="telephone">
					<tn-input v-model="form.telephone" />
				</tn-form-item>
				<!-- <tn-form-item label="车型：" prop="carTypeName">
					<tn-input type="select" :selectOpen="carTypeSelectShow" @click="carTypeSelectShow = true"
						v-model="form.carTypeName" />
				</tn-form-item> -->
				<tn-form-item label="车牌：" prop="carNum">
					<view style="width: 100%;min-height: 2em;" @click="carNumShow = true">{{form.carNum}}</view>
				</tn-form-item>
				<tn-form-item label="高速路段：" prop="highSpeed">
					<tn-input type="select" :selectOpen="gsSelectShow" @click="gsSelectShow = true"
						v-model="form.highSpeed" />
				</tn-form-item>
				<tn-form-item label="方向：" prop="direction">
					<tn-input v-model="form.direction" type="select" :selectOpen="fxSelectShow"
						@click="fxSelectShow = true" />
				</tn-form-item>
        <view class="tn-flex">
          <tn-form-item  label="桩号：" prop="startPoint">
            K<tn-input input-align="center" type="number" v-model="form.startPoint" />
          </tn-form-item>
          <tn-form-item label="" prop="endPoint">
            +<tn-input input-align="center" type="number" v-model="form.endPoint" />
          </tn-form-item>
        </view>
				<tn-form-item label="保通保畅应急大队：" prop="depart">
					<tn-input v-model="form.depart" type="select" :selectOpen="bcSelectShow"
						@click="bcSelectShow = true" />
				</tn-form-item>
		<tn-form-item label="救援公司：" prop="rescueCompany">
		  <tn-input v-model="form.rescueCompany"></tn-input>
		</tn-form-item>
        <tn-form-item label="救援人员：" prop="jyPersons">
          <view class="tn-flex tn-flex-direction-column">
            <tn-tag shape="radius" backgroundColor="#0a47c4" fontColor="#fff" v-for="(item, index) of jyPersons" :key="item.value" margin="10rpx"
                    width="auto" class="tn-padding-right-sm">
              <view class="tn-flex tn-flex-direction-row tn-flex-col-center tn-flex-row-center">
                <view>{{ item.label }}</view>
                <view class="tn-margin-left-lg tn-text-xs" @click="remove(index)">删除</view>
              </view>
            </tn-tag>
          </view>
          <tn-input type="select" :selectOpen="selectShow" @click="selectShow = true"></tn-input>
        </tn-form-item>
        <tn-form-item label="填报人员：" prop="fillPerson">
		  <tn-input type="select" v-model="form.fillPerson" :selectOpen="tianbaoselectShow" @click="tianbaoselectShow = true"></tn-input>
        </tn-form-item>
				<tn-form-item label="结案日期：" prop="closingDate">
					<uni-datetime-picker :clearIcon="false" :border="false" type="date" placeholder="请选择结案日期"
						v-model="form.closingDate" />
				</tn-form-item>
        <tn-form-item label="归档日期：" prop="archiveDate">
          <uni-datetime-picker :clearIcon="false" :border="false" type="date" placeholder="请选择归档日期"
                               v-model="form.archiveDate" />
        </tn-form-item>
				<tn-form-item label="保管期限：" prop="storeYear">
					<tn-input  input-align="center" type="number" v-model="form.storeYear" />
					年
				</tn-form-item>

        <view class="tn-flex">
          <tn-form-item label="卷内共：" prop="pieceNum">
            <tn-input  input-align="center" type="number" v-model="form.pieceNum" />
            件
          </tn-form-item>
          <tn-form-item label="" prop="jnpageNum">
            <tn-input  input-align="center" type="number" v-model="form.jnpageNum" />
            页
          </tn-form-item>
        </view>
				<view class="tn-flex tn-flex-row-center tn-padding-xl">
				  <tn-button @click="submit" backgroundColor="tn-bg-blue" style="width: 80%" fontColor="tn-color-white">保存
				  </tn-button>
				</view>
			</tn-form>
		</view>
		<!-- 救援类型 -->
		<tn-action-sheet :list="actionSheetList" v-model="jiuyuanleixingshow"
			@click="actionSheetCallback"></tn-action-sheet>

		<!-- 救援人员select -->
		<view v-show="selectShow">
			<tn-select v-model="selectShow" mode="single" :list="selectList"
				@confirm="goodsTypeSelectConfirm"></tn-select>
		</view>

		<!-- 填报人员select -->
		<view v-show="tianbaoselectShow">
			<tn-select v-model="tianbaoselectShow" mode="single" :list="selectList"
				@confirm="tainbaoTypeSelectConfirm"></tn-select>
		</view>

		<!-- 高速select -->
		<view v-show="gsSelectShow">
			<tn-select v-model="gsSelectShow" mode="single" :list="gsSelectList" @confirm="gsConfirm"></tn-select>
		</view>

		<!-- 车型select -->
		<view v-show="carTypeSelectShow">
			<tn-select v-model="carTypeSelectShow" mode="single" :list="carTypeSelectList" @confirm="carTypeSelectConfirm"></tn-select>
		</view>

		<!-- 方向select -->
		<view v-show="fxSelectShow">
			<tn-select v-model="fxSelectShow" mode="single" :list="fxSelectList" @confirm="fxConfirm"></tn-select>
		</view>

		<!-- 保畅大队select -->
		<view v-show="bcSelectShow">
			<tn-select v-model="bcSelectShow" mode="single" :list="bcSelectList"
				@confirm="(event) => (form.depart = event[0].label)"></tn-select>
		</view>

    <!--  车牌  -->
    <tn-keyboard mode="car" v-model="carNumShow" @change="carNumChange" @backspace="()=>form.carNum=form.carNum.slice(0,-1)"></tn-keyboard>
	<tn-modal v-model="erweima" :custom="true">
      <view class="custom-modal-content tn-flex tn-flex-direction-column tn-flex-col-center">
		<p style="margin-bottom: 8px;">卷宗卷皮</p>
		<canvas id="qrcode" canvas-id="qrcode" style="width: 200px; height: 200px;"></canvas>
		<tn-button @click="downloadPDFFn" backgroundColor="tn-bg-blue" style="width: 80%;margin-top: 16px;" fontColor="tn-color-white">
			下载PDF
		</tn-button>
      </view>
    </tn-modal>
	</view>
</template>

<script>
	import recorder from '@/components/recorder/index.vue';
	import UQRCode from '@/node_modules/uqrcodejs/uqrcode.js';
	import config from '@/config';
	import {
		addJyBase,
		getJyBase,
		updateJyBase
	} from '@/api/rescue.js';
	import {
		userList
	} from '@/api/login.js';
	import {
		ggjRoad
	} from '@/static/mock/gaosu.js';
	import {
		fangxiang
	} from '@/static/mock/fangxiang.js';
	import {
		carType
	} from '@/static/mock/carType.js';
	import {
		dadui
	} from '@/static/mock/dadui.js';
	import {
		rulses
	} from './juanzong';
	import dayjs from 'dayjs';
  import {downPdf, erweimaUrl} from "@/api/exam";
  import {toast} from "@/utils/common";
  import {saveNextStep} from "@/pages/rescue/add/funtion";


	export default {
		components: {
			recorder
		},
		data() {
			return {
				isHttps: false,
				dragAddress: '',
				tianbaoselectShow: false,

				erweima: false,
				// 车牌键盘
				carNumShow: false,

				// 高速
				gsSelectShow: false,
				gsSelectList: ggjRoad,

				carTypeSelectShow: false,
				carTypeSelectList: [...carType],

				// 方向
				fxSelectShow: false,
				fxSelectList: [...fangxiang],

				// 救援人员
				selectShow: false,
				selectList: [],

				// 保畅大队
				bcSelectShow: false,
				bcSelectList: [...dadui],

				url: '',
				jiuyuanleixingshow: false,
				actionSheetList: [{
						text: '车辆故障'
					},
					{
						text: '交通事故'
					}
				],
				jyPersons: [],
				form: {
					jyPersons: [],
					carNum: '',
					rescueCompany: '',
					accidentType: '车辆故障',
					caller: '',
					telephone: '',
					happenTime: '',

					highSpeed: 'G18荣乌高速',
					direction: '天津方向',
					startPoint: '',
					endPoint: '',
					recNum: '',
					fillPerson: '',
					depart: '徐水保通保畅应急大队',
					occutTime: '',
					archiveDate: '',

					closingDate: '',
					storeYear: '30',
					pieceNum: '6',
					jnpageNum: '6',

					carType: "3240737998816256",
					carTypeName: "轿车",
				},
				rules: rulses(this)
			};
		},
		onNavigationBarButtonTap(e) {
      // 08.12 解决卷宗修改车牌，数据不同步问题
      this.submit('pdf')
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.isHttps = window.location.protocol === 'https:'
			this.getUserList();
			this.$refs.form.setRules(this.rules);
			uni.getStorage({
				key: 'TIANBAOID',
				success: (res) => {
					if (res.data) {
						this.getList(res.data);
					}
				},
        fail: (res) => {
          //解决 时间不回显问题
            setTimeout(()=>{
              this.form.occutTime =dayjs().format('YYYY-MM-DD HH:mm:ss')
              this.form.archiveDate =dayjs().format('YYYY-MM-DD')
              this.form.closingDate =dayjs().format('YYYY-MM-DD')
            }, 500)
          }
			});
			uni.getStorage({
				key: 'userInfo',
				success: (res) => {
					if (res.data) {
						this.form.fillPerson = res.data.realName
					}
				}
			});
			this.gsConfirm(ggjRoad)
		},
		methods: {
			getRecorderData(res){
				console.log('res',res);
				Object.keys(res).forEach(key=>{
					if(key === '当事人'){
						this.form.caller = res[key];
					}
					if(key === '手机号'){
						this.form.telephone = res[key];
					}
					if(key === '车牌'){
						this.form.carNum = res[key];
					}
					if(key === '桩号'){
						this.form.startPoint = res[key];
					}
					if(key === '救援公司'){
						this.form.rescueCompany = res[key];
					}
					if(key === '填报人员'){
						this.form.fillPerson = res[key];
					}
				})
			},
			downloadPDFFn() {
				const fileUrl =downPdf({
              baseId:this.form.id,
              typeName: 'base',
              id:undefined
            })
				// console.log(fileUrl, 'vvvvvvvvvvvv');
				// 创建一个隐藏的 <a> 元素用于下载
				const link = document.createElement('a');
				link.href = fileUrl;
				link.download = '卷宗卷皮.pdf'; // 设置下载的文件名
				link.style.display = 'none';
				document.body.appendChild(link);
				link.click();
				document.body.removeChild(link);
				uni.showToast({
					title: '下载成功',
					icon: 'success'
				});
			},
			creatImg() {
				// 获取uQRCode实例
				var qr = new UQRCode();
				// 设置二维码内容
				qr.data = erweimaUrl({
          baseId:this.form.id,
          typeName: 'base',
          id:undefined
        });
				// 设置二维码大小，必须与canvas设置的宽高一致
				qr.size = 200;
				// 调用制作二维码方法
				qr.make();
				// 获取canvas上下文
				var canvasContext = uni.createCanvasContext('qrcode', this); // 如果是组件，this必须传入
				// 设置uQRCode实例的canvas上下文
				qr.canvasContext = canvasContext;
				// 调用绘制方法将二维码图案绘制到canvas上
				qr.drawCanvas();
			},
			carNumChange(e){
				this.form.carNum += e;
			},
			generatePDF() {
				this.$refs.pdfGenerator.generatePdf()
			},
			handleDownload() {
				// 下载前的钩子（可进行日志记录或其他操作）
				console.log("PDF生成开始")
			},
			gsConfirm(val) {
				this.form.direction = '';
				this.form.depart = '';
				this.form.highSpeed = val[0].label;
				this.fxConfirm(this.fxSelectList);
			},
			carTypeSelectConfirm(val){
				console.log(val[0]);
				this.form.carType = val[0].value;
				this.form.carTypeName = val[0].label;
			},
			fxConfirm(val) {
				this.form.depart = '';
				this.form.direction = val[0].label;
				this.getBaoChang(val[0].value);
			},
			getFangXiang(id) {
				this.fxSelectList = fangxiang.filter((item) => item.roadId === id);
			},
			getBaoChang(id) {
				this.bcSelectList = dadui.filter((item) => item.roadHeadId === id);
				this.form.depart = this.bcSelectList[0]['label']
			},
			remove(index) {
				this.jyPersons.splice(index, 1);
			},
			getUserList() {
				userList({
					current: 1,
					size: 999
				}).then((res) => {
					const arr = [];
					res.data.records.forEach((item) => {
						arr.push({
							value: item.id,
							label: item.realName
						});
					});
					this.selectList = arr;
				});
			},
			goodsTypeSelectConfirm(event) {
				this.jyPersons = [...this.jyPersons, ...event];
			},
			tainbaoTypeSelectConfirm(event) {
				this.form.fillPerson = event[0].label;
			},
			getList(id) {
				getJyBase(id).then((res) => {
					this.form = res.data;
					this.dragAddress = true;
					this.jyPersons = this.form.jyPersons.map((item, index) => {
						return {
							value: item.jyPersonId,
							label: item.jyPersonName
						};
					});
				});
			},
			// 点击actionSheet回调
			actionSheetCallback(index) {
				this.form.accidentType = this.actionSheetList[index].text;
			},
			submit(type) {
				this.$refs.form.validate((valid) => {
					if (valid) {
						this.form.jyPersons = [];
						let arr = [];
						this.jyPersons.forEach((item) => {
							arr.push({
								jyPersonId: item.value,
								jyPersonName: item.label
							});
							this.form.jyPersons = arr;
						});
            // 有ID就更新，没ID就添加
						if (this.form.id != null) {
							updateJyBase(this.form).then((res) => {
                saveNextStep(type, res, this)
							});
						} else {
							addJyBase(this.form).then((res) => {
								uni.setStorage({
								  key: 'TIANBAOID',
								  data: res.data.id
								});
                saveNextStep(type, res, this)
              });
						}
						console.log('验证通过');
					} else {
						console.log('验证失败');
					}
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	.card {
		background-color: #fff;
		box-shadow: 0px 4px 20px 0px rgba(0, 3, 72, 0.1);
		border-radius: 8px;
	}

	.pdf-con {
		margin: 50px 10% 50px 10%;
		width: 100%;
		border: 3px double #666;

		.title {
			font-size: 24px;
			font-weight: 400;
			text-align: center;
			border-bottom: 1px solid #666;
		}
	}
	::v-deep{
		.tn-form-item--left__content__label{
			font-weight: 700;
		}
	}
</style>
